package com.imdroid.lite.net.udp;

import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.util.Log;

import com.imdroid.carac.audioCodec.UDPSpeaker;
import com.imdroid.lite.activities.TeamMapActivity;
import com.imdroid.lite.model.Team;
import com.imdroid.lite.model.TeamMember;
import com.imdroid.lite.process.PlaySoundProcess;

public class NotificationGenerator {
	private static String TAG = "NotificationGenerator";

	/**
	 * 实际执行工作的线程组
	 */
	private static ExecutorService workers;

	public static void startupNotificationWorkers(int workerCount) {
		if (workers != null) {
			System.out
					.println("Workers are working very hard already, please don't squeeze any more ... ");
			return;
		}
		workers = Executors.newFixedThreadPool(workerCount);
	}

	public static void shutdownNotificationWorkers() {
		if (workers != null) {
			workers.shutdown();
			workers = null;
		}
	}

	public static void tryGenerateNotification(final DatagramPacket packet) {
		workers.execute(new Runnable() {
			public void run() {
				byte[] data = packet.getData();
				if ((data[0] & 1) != 0) {
					// 确认包、回执，暂不处理
					return;
				}

				byte type = data[1];
				Log.d(TAG, "Type------3---->" + type);
				switch (type) {
				case FileTypes.CALL:
					// 没有了
					break;
				case FileTypes.DESTINATION:
					// 非车机，没有
					break;
				case FileTypes.CONNECT:
					// Toast信息提示用户登陆成功(服务器回复的心跳信息)

					break;
				case FileTypes.IDA_AUDIO:
					// 音频文件，整个文件的发，现在也没有了，
					// long msgId = IntegerTransfer.byteToLong(packet.getData(),
					// 2);
					// short part =
					// IntegerTransfer.byteToShort(packet.getData(), 20);
					// FileReceiver.getInstance(msgId, part).process(packet,
					// part);
					break;
				case FileTypes.IMAGE:
					// 接收图片，现在没有
					break;
				case FileTypes.TAKING_PICTURE:
					// 非车机版，没有被请求拍照的功能
					break;
				case FileTypes.TEAM_JOIN:
					// 有队员加入队伍
					joinTeam();
					break;
				case FileTypes.TEAM_CONFIRMED:
					// 邀请被确认，现在没有了
					break;
				case FileTypes.TEAM_CANCEL:
					// 队伍被队长解散，退出队伍，退出地图。现在没有了。
					break;
				case FileTypes.TEAM_DESTINATION:
					Log.d(TAG, "teamDestInfo -" + 1111);
					// 接收到队伍的目的地
					String[] teamDestInfo = null;
					try {
						String text = new String(packet.getData(), 2, packet
								.getLength() - 2, "UTF-8");
						Log.d(TAG, "teamDestInfo - " + text);
						teamDestInfo = text.split("&&");
					} catch (UnsupportedEncodingException e1) {
						e1.printStackTrace();
					}
					if (teamDestInfo != null && teamDestInfo.length > 3)
						recevieTeamDestination(teamDestInfo[0],
								Float.parseFloat(teamDestInfo[1]),
								Float.parseFloat(teamDestInfo[2]),
								teamDestInfo[3].trim().equals("1"));
					break;
				case FileTypes.TEAM_EXIT:
					// 有队友退出队伍
					exitTeam();
					break;
				case FileTypes.TEAM_LOCATION:
					// 队友位置更新
					int fromUser = IntegerTransfer.byteToInt(packet.getData(),
							10);
					try {
						String[] info = new String(packet.getData(), 18, packet
								.getLength() - 18, "UTF-8").split("&&");
						updateTeamLocation(info, fromUser);
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					break;
				case FileTypes.REAL_TIME:
					// 收到实时语音包
					int realTimeSender = IntegerTransfer.byteToInt(
							packet.getData(), 10);
					byte[] audio = new byte[packet.getLength() - 18];
					System.arraycopy(packet.getData(), 18, audio, 0,
							audio.length);
					UDPSpeaker.addData(realTimeSender, audio);

					if (TeamMapActivity.instance != null) {
						try {

							if (realTimeSender != 0)
								TeamMapActivity.instance
										.showMember(realTimeSender);
							// 静音
							if (TeamMapActivity.instance.isMute())
								return;
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					break;
				}
			}
		});
	}

	private static void updateTeamLocation(String[] info, int fromUser) {
		// info[0] Team id
		// info[1] latitude
		// info[2] longitude
		// info[3] speed
		// info[4] userName
		// info[5] direction
		// info[6] device type
		Team team = Team.getCurrentTeam();
		if (team == null || team.getMembers() == null)
			return;
		Log.d(TAG, "Team Member Location Update---" + fromUser);

		TeamMember member = team.getMembers().get(fromUser);
		if (member != null) {
			member.setLat(Float.parseFloat(info[1]));
			member.setLon(Float.parseFloat(info[2]));
			member.setSpeed(Float.parseFloat(info[3]));
			member.setDirect(Float.parseFloat(info[5]));
		}
		// 刷新队员列表
		TeamMapActivity instance = TeamMapActivity.instance;
		if (instance != null && instance.isActive()) {
			instance.getHandler().sendEmptyMessage(
					TeamMapActivity.EVENT_TEAM_UPDATE);
		}
	}

	/**
	 * Other team member confirm to join
	 */
	private static void joinTeam() {
		// 播放声音
		PlaySoundProcess.playSound(PlaySoundProcess.confirm);
		// 刷新队员列表
		TeamMapActivity instance = TeamMapActivity.instance;
		if (instance != null && instance.isActive()) {
			instance.getHandler().sendEmptyMessage(
					TeamMapActivity.EVENT_TEAM_REFRESH);
		}
	}

	/**
	 * Receive the desiniation
	 * 
	 * @param destination
	 *            the name of destination
	 * @param lat
	 *            latitude of the destination
	 * @param lon
	 *            longitude of the destination
	 * @param routeSearch
	 *            if need the search the route when setting the desination
	 */
	private static void recevieTeamDestination(String destination, float lat,
			float lon, boolean routeSearch) {
		if (Team.getCurrentTeam() != null) {
			Team.getCurrentTeam().setDestinationName(destination);
			Team.getCurrentTeam().setDestinationLat(lat);
			Team.getCurrentTeam().setDestinationLon(lon);
			Team.getCurrentTeam().setSearchRoute(routeSearch);

			PlaySoundProcess.playSound(PlaySoundProcess.confirm);
			TeamMapActivity instance = TeamMapActivity.instance;

			instance.getHandler().sendEmptyMessage(
					TeamMapActivity.EVENT_TEAM_RECEIVE_LOCATION);
		}
	}

	/**
	 * 退出队伍
	 */
	private static void exitTeam() {
		// 播放声音
		PlaySoundProcess.playSound(PlaySoundProcess.exit);

		// 刷新队员列表
		TeamMapActivity instance = TeamMapActivity.instance;
		if (instance != null && instance.isActive()) {
			instance.getHandler().sendEmptyMessage(
					TeamMapActivity.EVENT_TEAM_REFRESH);
		}
	}
}
